<template>
  <div class="jsbos-common-layout">
    <div class="jsbos-common-layout-left">
      <div class="jsbos-common-title">
        <h2>{{ $t("common.questionnaireType") }}</h2>

        <span class="options">
          <el-dropdown>
            <el-link icon="icon-ym icon-ym-mpMenu" :underline="false" />
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="getQuestionnaireTypeList()"
                >刷新数据</el-dropdown-item
              >
              <el-dropdown-item @click.native="toggleExpand(true)"
                >展开全部</el-dropdown-item
              >
              <el-dropdown-item @click.native="toggleExpand(false)"
                >折叠全部</el-dropdown-item
              >
              <!-- <el-dropdown-item @click.native="addQuestionnaireType()"
                >新增分类</el-dropdown-item
              > -->
            </el-dropdown-menu>
          </el-dropdown>
          &nbsp;
          <el-tooltip effect="light" content="新增" placement="top">
            <el-link
              icon="icon-ym icon-ym-btn-add"
              @click="addQuestionnaireType()"
            />
          </el-tooltip>
        </span>
      </div>
      <div class="jsbos-common-tree-search-box">
        <el-input
          placeholder="输入关键字"
          v-model="filterText"
          suffix-icon="el-icon-search"
          clearable
        />
      </div>
      <el-scrollbar
        class="jsbos-common-el-tree-scrollbar"
        v-loading="treeLoading"
      >
        <el-tree
          ref="treeBox"
          :data="treeData"
          :props="defaultProps"
          :default-expand-all="expands"
          highlight-current
          :expand-on-click-node="false"
          node-key="id"
          @node-click="handleNodeClick"
          class="jsbos-common-el-tree"
          v-if="refreshTree"
          :filter-node-method="filterNode"
        >
          <span
            class="custom-tree-node"
            slot-scope="{ data, node }"
            :title="data.name"
            @mouseenter="mouseEnter(data, true)"
            @mouseleave="mouseEnter(data, false)"
          >
            <span class="text" :title="data.name">{{ node.label }}</span>
            <el-popover trigger="hover">
              <span>
                <i
                  class="icon-ym icon-ym-signature"
                  @click="editCategory(data)"
                />
                &nbsp;&nbsp;
                <i
                  class="icon-ym icon-ym-delete"
                  @click="delCategory(data.id)"
                />
              </span>
              <div slot="reference" class="ellipsis-trigger">...</div>
            </el-popover>
          </span>
        </el-tree>
      </el-scrollbar>
    </div>
    <div class="jsbos-common-layout-center">
      <el-row class="jsbos-common-search-box" :gutter="16">
        <el-form @submit.native.prevent>
          <el-col :span="5">
            <el-form-item label="关键字">
              <el-input
                v-model="query.keyWord"
                placeholder="请输入编码或名称"
                clearable
                @keyup.enter.native="search"
              >
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                @click.native.prevent="search"
                >查询</el-button
              >
              <el-button icon="el-icon-refresh-right" @click="reset()"
                >重置</el-button
              >
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="jsbos-common-layout-main jsbos-flex-main">
        <div class="jsbos-common-head">
          <div>
            <el-button
              type="primary"
              icon="el-icon-plus"
              @click="addOrUpdateHandle()"
              >新增
            </el-button>
            <!-- <el-button type="text" icon="el-icon-download" @click="exportData()"
              >导出
            </el-button> -->
          </div>
          <div class="jsbos-common-head-right">
            <el-tooltip effect="dark" content="刷新" placement="top">
              <el-link
                icon="icon-ym icon-ym-Refresh JSBOS-common-head-icon"
                :underline="false"
                @click="reset()"
              />
            </el-tooltip>
            <el-tooltip effect="dark" content="配置" placement="top">
              <el-link
                icon="icon-ym icon-ym-system jsbos-common-head-icon"
                :underline="false"
                @click="toSettings()"
              />
            </el-tooltip>
            <ScreenFull isContainer />
          </div>
        </div>
        <jsbos-table v-loading="listLoading" :data="list">
          <!-- <el-table-column prop="questCode" label="模板代码" width="80" align="left" /> -->
          <el-table-column
            prop="questName"
            label="模板名称"
            width="0"
            align="left"
          >
            <template slot-scope="scope">
              <el-link
                type="primary"
                :underline="false"
                @click="goDetail(scope.row.id)"
              >
                {{ scope.row.questName }}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column
            label="模板分类"
            width="0"
            prop="questionnaireTypeId"
            algin="left"
          >
          </el-table-column>
          <el-table-column
            prop="description"
            label="模板描述"
            width="200"
            align="left"
            :show-overflow-tooltip="true"
          />

          <el-table-column
            prop="creatorUserId"
            label="创建用户"
            width="0"
            align="left"
          />
          <el-table-column
            prop="creatorTime"
            label="创建时间"
            width="0"
            align="left"
          />
          <el-table-column label="操作" width="150" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" @click="addOrUpdateHandle(scope.row.id)"
                >编辑
              </el-button>
              <el-button
                type="text"
                class="jsbos-table-delBtn"
                @click="handleDel(scope.row.id)"
                >删除
              </el-button>
              <!-- <el-button type="text" @click="goDetail(scope.row.id)"
                >详情
              </el-button> -->
            </template>
          </el-table-column>
        </jsbos-table>
        <pagination
          :total="total"
          :page.sync="listQuery.currentPage"
          :limit.sync="listQuery.pageSize"
          @pagination="initData"
        />
      </div>
    </div>
    <JSBOS-Form v-if="formVisible" ref="JSBOSForm" @refresh="refresh" />
    <ExportBox v-if="exportBoxVisible" ref="ExportBox" @download="download" />
    <Detail
      v-if="detailVisible"
      ref="Detail"
      @refresh="detailVisible = false"
    />
    <DeviceTypeForm
      v-if="formTypeVisible"
      ref="formTypeVisible"
      @refresh="refreshDeviceType"
    />
    <LeadSetting v-if="settingVisible" ref="LeadSetting" @close="refresh" />
  </div>
</template>

<script>
import LeadSetting from "./LeadSetting.vue";
import request from "@/utils/request";
import JSBOSForm from "./Form";
import { getTypeListTree, delQuestionnaireType } from "../api";
import ExportBox from "./ExportBox";
import Detail from "./Detail";
import DeviceTypeForm from "./QuestionnaireTypeForm.vue";
import "../styles/index.scss";
import { isEmpty } from "@/utils/isEmpty";

export default {
  components: { JSBOSForm, ExportBox, DeviceTypeForm, Detail, LeadSetting },
  data() {
    return {
      drawer: false,
      settingVisible: false,
      formTypeVisible: false,
      treeLoading: true,
      expands: true,
      refreshTree: true,
      treeData: [],
      defaultProps: {
        children: "children",
        label: "name",
        value: "id",
      },
      detailVisible: false,
      query: {
        keyWord: undefined,
        questionnaireTypeId: undefined,
      },
      treeProps: {
        children: "children",
        label: "name",
        value: "id",
      },
      list: [],
      listLoading: true,
      total: 0,
      listQuery: {
        currentPage: 1,
        pageSize: 20,
        sort: "desc",
        sidx: "creatorTime",
      },
      formVisible: false,
      exportBoxVisible: false,
      filterText: "",
      columnList: [
        { prop: "questCode", label: "问卷模板代码" },
        { prop: "questName", label: "问卷模板名称" },
        { prop: "questionnaireTypeId", label: "所属分类ID" },
        { prop: "description", label: "问卷模板描述" },
        { prop: "creatorUserId", label: "创建用户" },
        { prop: "creatorTime", label: "创建时间" },
      ],
      questionnaireTypeIdOptions: [],
      questionnaireTypeIdProps: {
        label: "name",
        value: "id",
        children: "children",
      },
    };
  },
  computed: {
    menuId() {
      return this.$route.meta.modelId || "";
    },
  },
  created() {
    this.initData();
    this.getQuestionnaireTypeList(true);
  },
  watch: {
    filterText(val) {
      this.$refs.treeBox.filter(val);
    },
  },
  methods: {
    toSettings() {
      this.drawer = true;
      this.settingVisible = true;
      this.$nextTick(() => {
        this.$refs.LeadSetting.init();
      });
    },
    goDetail(id) {
      this.detailVisible = true;
      this.$nextTick(() => {
        this.$refs.Detail.init(id);
      });
    },
    delCategory(id) {
      this.handleDelType(id);
    },
    handleDelType(id) {
      this.$confirm(this.$t("common.delTip"), this.$t("common.tipTitle"), {
        type: "warning",
      })
        .then(() => {
          delQuestionnaireType(id).then((res) => {
            if (!isEmpty(res.data)) {
              this.$message({
                type: "warning",
                message: "此数据有关联数据，请勿删除！",
                duration: 1500,
              });
            } else {
              this.$message({
                type: "success",
                message: res.msg,
                duration: 1500,
                onClose: () => {
                  this.getQuestionnaireTypeList(true);
                },
              });
            }
          });
        })
        .catch(() => {});
    },
    editCategory(data) {
      this.addOrUpdateTypeHandle(data.id);
    },
    addOrUpdateTypeHandle(id, isDetail) {
      this.formTypeVisible = true;
      this.$nextTick(() => {
        this.$refs.formTypeVisible.init(id, isDetail);
      });
    },
    //新增分类
    addQuestionnaireType(data) {
      this.formTypeVisible = true;
      this.$nextTick(() => {
        this.$refs.formTypeVisible.init(data ? data.id : null, null, 1);
      });
    },
    refreshDeviceType() {
      this.getQuestionnaireTypeList();
      this.initData();
    },
    mouseEnter(data, show) {
      // if (data.parentId != "0" && data.parentId != "-1") {
      data.ifShow = show;
      // }
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    handleNodeClick(data) {
      this.query.questionnaireTypeId = data.id;
      this.search();
    },
    //折叠展开树
    toggleExpand(expands) {
      this.refreshTree = false;
      this.expands = expands;
      this.$nextTick(() => {
        this.refreshTree = true;
        this.$nextTick(() => {
          this.$refs.treeBox.setCurrentKey(this.parentId);
        });
      });
    },
    //获取树数据
    getQuestionnaireTypeList(isInit) {
      this.treeLoading = true;
      var data = {
        parentId: "-1",
      };
      getTypeListTree(data)
        .then((res) => {
          this.treeData = res.data;
          this.questionnaireTypeIdOptions = res.data;
          this.$nextTick(() => {
            if (!this.treeData.length) {
              this.treeLoading = false;
              this.listLoading = false;
              return;
            }
            if (isInit) this.parentId = this.treeData[0].id;
            this.$refs.treeBox.setCurrentKey(this.parentId);
            this.treeLoading = false;
            if (isInit) this.initData();
          });
        })
        .catch(() => {
          this.treeLoading = false;
        });
    },
    sortChange({ column, prop, order }) {
      this.listQuery.sort = order == "ascending" ? "asc" : "desc";
      this.listQuery.sidx = !order ? "" : prop;
      this.initData();
    },
    initData() {
      this.listLoading = true;
      let _query = {
        ...this.listQuery,
        ...this.query,
        menuId: this.menuId,
      };
      request({
        url: `/api/questionnaire/OqQuestionnaire/getList`,
        method: "post",
        data: _query,
      }).then((res) => {
        var _list = [];
        for (let i = 0; i < res.data.list.length; i++) {
          let _data = res.data.list[i];
          _list.push(_data);
        }
        this.list = _list;
        this.total = res.data.pagination.total;
        this.listLoading = false;
      });
    },
    handleDel(id) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        type: "warning",
      })
        .then(() => {
          request({
            url: `/api/questionnaire/OqQuestionnaire/${id}`,
            method: "DELETE",
          }).then((res) => {
            this.$message({
              type: "success",
              message: res.msg,
              onClose: () => {
                this.initData();
              },
            });
          });
        })
        .catch(() => {});
    },
    addOrUpdateHandle(id, isDetail) {
      this.formVisible = true;
      this.$nextTick(() => {
        this.$refs.JSBOSForm.init(id, isDetail);
      });
    },
    exportData() {
      this.exportBoxVisible = true;
      this.$nextTick(() => {
        this.$refs.ExportBox.init(this.columnList);
      });
    },
    download(data) {
      let query = {
        ...data,
        ...this.listQuery,
        ...this.query,
        menuId: this.menuId,
      };
      request({
        url: `/api/questionnaire/OqQuestionnaire/Actions/Export`,
        method: "GET",
        data: query,
      }).then((res) => {
        if (!res.data.url) return;
        this.jsbos.downloadFile(res.data.url);
        this.$refs.ExportBox.visible = false;
        this.exportBoxVisible = false;
      });
    },
    search() {
      this.listQuery = {
        currentPage: 1,
        pageSize: 20,
        sort: "desc",
        sidx: "creatorTime",
      };
      this.initData();
    },
    refresh(isrRefresh) {
      this.formVisible = false;
      if (isrRefresh) this.reset();
    },
    reset() {
      this.$refs.treeBox.setCurrentKey(null);
      for (let key in this.query) {
        this.query[key] = undefined;
      }
      this.search();
    },
  },
};
</script>

<style scoped>
.ellipsis-trigger {
  cursor: pointer;
  display: inline-block;
  font-size: 18px;
  /* 调整字体大小 */
}

.ellipsis-trigger:hover {
  color: #409eff;
  /* 悬停时改变颜色（可选） */
}
</style>
